import { useState, useEffect } from 'react';
import Taro, { useLoad, useRouter } from '@tarojs/taro';
import { View, Text, Image, Picker } from '@tarojs/components';
import { AtInput, AtForm, AtIcon } from 'taro-ui';
import IconFont from '@/components/iconfont';
import api from "@/service/apiRequest"
import { useUserInfo } from '@/hooks/useUserInfo';
import { requestUploadFile } from '@/utils/common';

import "taro-ui/dist/style/components/form.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/icon.scss";
import './index.scss';

function PetEdit() {
  const router = useRouter();
  // const petTypes = ['狗', '猫', '兔子', '仓鼠', '其他'];
  const [petTypes, setPetTypes] = useState<any[]>([]);
  const { userInfo } = useUserInfo();
  const [petInfo, setPetInfo] = useState<PetInfo>({
    petName: "",
    petType: "",
    petCategoryId: null,
    petBreed: "",
    birthDate: "",
    petGender: "",
    petWeight: "",
    petAvatarIcon: "",
  });

  useLoad(() => {
    getPetTypes();
  })

  useEffect(() => {
    // 如果是编辑已有宠物，获取宠物信息
    if (router.params && router.params.id) {
      getPetInfo(router.params.id);
    }
  }, [router.params]);
  
  const getPetInfo = async (id) => {
    let res = await api.get(`/api/pets/index/${id}`);
		setPetInfo(res);
  };

  const getPetTypes = async () => {
    let res = await api.get(`/api/pet_encyclopedias/categories`);
    if (res && Array.isArray(res)) {
      let petTypes = res.map(item => Object.assign({id: item.id, name: item.cateName}));
      setPetTypes(petTypes);
      setPetInfo(prev => ({...prev, petType: petTypes[0].name, petCategoryId: petTypes[0].id}));
    }
  }
  
  const handleInputChange = (key: keyof PetInfo, value: string) => {
    setPetInfo(prev => ({ ...prev, [key]: value }));
    return value;
  };
  
  const handleTypeChange = (e) => {
    const selectedPet = petTypes[e.detail.value];
    setPetInfo(prev => ({ ...prev, petType: selectedPet.name, petBreed: "", petCategoryId: selectedPet.id }));
  };
  
  const handleDateChange = (e) => {
    setPetInfo(prev => ({ ...prev, birthDate: e.detail.value }));
  };
  
  const chooseImage = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        let petAvatarIcon = res.tempFilePaths[0];
        let fileName = petInfo.petAvatarIcon ? petAvatarIcon.substring(petInfo.petAvatarIcon.lastIndexOf('/')+1) : `pet_avatar_${userInfo.pid}_${petAvatarIcon.substring(petAvatarIcon.lastIndexOf('/')+1)}`;
        let result: any = await requestUploadFile(petAvatarIcon, fileName);
        if (result.data) {
          setPetInfo(prev => ({ ...prev, petAvatarIcon: result.data }));
        }
      }
    });
  };

  const requestPetInfo = async () => {
    let params = {
      userId: userInfo.userId,
      ...petInfo,
    };
    let response = await api.post(`/api/pets/edit`, params);    
    return response.result;
  }
  
  const handleSubmit = async () => {
    const { petName, petGender, petBreed, birthDate, petWeight } = petInfo;
    
    // 表单验证
    if (!petName) {
      Taro.showToast({ title: '请输入宠物名称', icon: 'none' });
      return;
    }

    if (!petGender) {
      Taro.showToast({ title: '请选择宠物性别', icon: 'none' });
      return;
    }
    
    if (!petBreed) {
      Taro.showToast({ title: '请输入宠物品种', icon: 'none' });
      return;
    }
    
    if (!birthDate) {
      Taro.showToast({ title: '请选择出生日期', icon: 'none' });
      return;
    }
    
    if (!petWeight) {
      Taro.showToast({ title: '请输入体重', icon: 'none' });
      return;
    }
    
    let result = await requestPetInfo();
    if(result) {
      Taro.showToast({ 
        title: '保存成功', 
        icon: 'success',
        duration: 2000,
        success: () => {
          Taro.navigateBack();
        }
      });
      
    }
    
  };
  
  return (
    <View className='pet-edit-container'>
      <View className='avatar-section'>
        {/* <Text className='page-title'>编辑宠物</Text> */}
        <View className='avatar-wrapper flex-c-c-c'>
          {
            petInfo.petAvatarIcon ? (
              <Image 
                src={petInfo.petAvatarIcon} 
                mode='aspectFill'
                onClick={chooseImage}
              />
            ) : (
              <IconFont name="pet-pawprint" size={40} />
            )
          }
        </View>
        <View
          className='upload-btn' 
          onClick={chooseImage}
        >
          上传头像
        </View>
      </View>
      
      <AtForm className='form-box'>
        <View className='form-item'>
          <View className='form-label'>宠物名称</View>
          <AtInput
            name='petName'
            type='text'
            placeholder='请输入宠物名称'
            cursor={-1}
            value={petInfo.petName}
            onChange={(value: string) => handleInputChange('petName', value)}
            className='form-input'
          />
        </View>

        <View className='form-item'>
          <View className='form-label'>性别</View>
          <View className='flex-b-c'>
            <View 
              className={petInfo.petGender == '0' ? 'form-item-card flex-c-c-c form-item-first-l form-item-active-card' : 'form-item-card flex-c-c-c form-item-first-l'}
              onClick={() => handleInputChange('petGender', '0')}
            >
              <IconFont name='pet-nan' size={45} color={petInfo.petGender == '0' ? '#ff7a59' : ''} />
              <View className='f-i-c-item'>男孩</View>
            </View>
            <View 
              className={petInfo.petGender == '1' ? 'form-item-card flex-c-c-c form-item-first-l form-item-active-card' : 'form-item-card flex-c-c-c form-item-first-l'}
              onClick={() => handleInputChange('petGender', '1')}
            >
              <IconFont name='pet-nv' size={45} color={petInfo.petGender == '1' ? '#ff7a59' : ''} />
              <View className='f-i-c-item'>女孩</View>
            </View>
          </View>
        </View>
        
        <View className='flex-b-c'>
          <View className='form-item form-item-first-l'>
            <View className='form-label'>宠物类型</View>
            <Picker
              mode='selector'
              range={petTypes}
              rangeKey='name'
              onChange={handleTypeChange}
              value={petTypes.findIndex(item => item.name == petInfo.petType)}
            >
              <View className='form-input form-select'>
                {petInfo.petType}
              </View>
            </Picker>
          </View>
          
          <View className='form-item'>
            <View className='form-label'>品种</View>
            <AtInput
              name='petBreed'
              type='text'
              placeholder='宠物品种'
              cursor={-1}
              value={petInfo.petBreed}
              onChange={(value: string) => handleInputChange('petBreed', value)}
              className='form-input'
            />
          </View>
        </View>

        <View className='flex-b-c'>
          <View className='form-item form-item-first-l'>
            <View className='form-label'>出生日期</View>
            <Picker
              mode='date'
              onChange={handleDateChange}
              value={petInfo.birthDate}
            >
              <View className='form-input date-picker'>
                <Text className='label-color'>{petInfo.birthDate || '出生日期'}</Text>
                <AtIcon value='calendar' size='20' className='date-icon' />
              </View>
            </Picker>
          </View>
          
          <View className='form-item'>
            <View className='form-label'>体重(kg)</View>
            <AtInput
              name='petWeight'
              type='digit'
              placeholder='宠物体重'
              cursor={-1}
              value={petInfo.petWeight}
              onChange={(value: string) => handleInputChange('petWeight', value)}
              className='form-input petWeight-input'
            />
          </View>
        </View>
        
        <View className='footer-bar-wrapper'>
          <View 
            className='submit-btn' 
            onClick={handleSubmit}
          >
            保存
          </View>
        </View>
      </AtForm>
    </View>
  );
};

export default PetEdit;